package csu.web.credit_bank.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import csu.web.credit_bank.mapper.StudentsMapper;
import csu.web.credit_bank.mapper.TeachersMapper;
import csu.web.credit_bank.pojo.Students;
import csu.web.credit_bank.pojo.Teachers;
import csu.web.credit_bank.pojo.User;
import csu.web.credit_bank.pojo.vo.SelectedCourseVO;
import csu.web.credit_bank.pojo.vo.UserLogin;
import csu.web.credit_bank.pojo.vo.UserUpdate;
import csu.web.credit_bank.service.CoursesService;
import csu.web.credit_bank.service.UsersService;
import csu.web.credit_bank.utils.JwtHelper;
import csu.web.credit_bank.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
public class UserController {
    @Autowired
    private UsersService usersService;
    @Autowired
    private JwtHelper jwtHelper; // 注入 JwtHelper 以便从 Token 中获取用户ID
    @Autowired
    private CoursesService coursesService;
    @Autowired
    private StudentsMapper studentsMapper;
    @Autowired
    private TeachersMapper teachersMapper;

    @PostMapping("/users")
    public Result register(@RequestBody User user) {
        return usersService.register(user);
    }
    @PutMapping(value = "users/{id}")
    public Result updateUser(
            @PathVariable String id,
            @RequestParam("username") String username,
            @RequestParam("email") String email,
            @RequestParam("birthDate") String birthDate,
            @RequestParam(value = "hobbies", required = false) String hobbies,
            @RequestPart(value = "image", required = false) MultipartFile image) {

            UserUpdate userUpdate = new UserUpdate();
            userUpdate.setUsername(username);
            userUpdate.setEmail(email);
            userUpdate.setBirthDate(this.parseDate(birthDate));
            userUpdate.setHobbies(hobbies);
            userUpdate.setImage(image);
            return usersService.updateUser(id, userUpdate);

    }
    private Date parseDate(String dateString) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.parse(dateString, formatter);
        Instant instant = localDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }
    @PostMapping("/token")
    public Result token(@RequestBody UserLogin userLogin) {
        return usersService.login(userLogin);
    }
    @GetMapping("/users/email/verification_code/{email}")
    public Result getVerificationCode(@PathVariable String email) {//发送邮件包含验证码，并返回验证码
        return usersService.getVerificationCode(email);
    }

    @PostMapping("/users/activate-auditor")
    public Result activateAuditor(@RequestBody Map<String, String> requestBody,
                                  @RequestHeader(value = "Authorization", required = false) String authorizationHeader) { // 修改为获取 Authorization 头
        String auditorPassword = requestBody.get("auditorPassword");
        if (auditorPassword == null || auditorPassword.isEmpty()) {
            return Result.failure("审核员密码不能为空");
        }

        // 修改此处：通过 JwtHelper 从 Authorization 头中解析 token
        String token = jwtHelper.getTokenFromHeader(authorizationHeader);

        if (token == null) {
            return Result.failure("认证失败，请提供有效的Token");
        }

        String userId = jwtHelper.getUserId(token); // 使用解析后的 token 获取 userId

        if (userId == null || "null".equals(userId)) {
            return Result.failure("无法获取用户信息，请重新登录或Token无效");
        }

        return usersService.activateAuditor(userId, auditorPassword);
    }
    @PostMapping("/users/{id}/signin")//签到
    public Result signIn(@PathVariable String id) {
        return usersService.signIn(id);
    }
    @GetMapping("/users/{id}/signin")//查询用户信息
    public Result getSignInfo(@PathVariable String id) {
        return usersService.getSignInfo(id);
    }

    /**
     * 【新增】获取指定用户选择的所有课程（学生用）
     */

    @GetMapping("/users/{userId}/selected-courses")
    public Result getSelectedCourses(
            @PathVariable String userId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "12") int size) {

        IPage<SelectedCourseVO> coursePage = coursesService.getSelectedCoursesByUserId(userId, page, size);
        return Result.success(coursePage);
    }

    @GetMapping("/users/{id}")
    public ResponseEntity<User> getUserById(@PathVariable String id) {
        System.out.println("Received request for user ID: " + id);
        User user = usersService.getUserById(id);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(user);
    }

    @GetMapping("/users/me")
    public Result getMyInfo(@RequestHeader("token") String token) {
        String userId = jwtHelper.getUserId(token);
        if (userId == null) {
            return Result.failure("无效的Token");
        }

        User user = usersService.getUserById(userId);
        if (user == null) {
            return Result.failure("用户不存在");
        }

        Map<String, Object> res = new HashMap<>();
        res.put("user", user);

        if (user.getUserType() == 0) { // 学生
            Students student = studentsMapper.selectOne(new QueryWrapper<Students>().eq("user_id", userId));
            res.put("student", student);
        } else if (user.getUserType() == 1) { // 教师
            Teachers teacher = teachersMapper.selectOne(new QueryWrapper<Teachers>().eq("user_id", userId));
            res.put("teacher", teacher);
        }
        return Result.success(res);
    }

    @GetMapping("/users/{id}/frame")
    public Result getUserFrame(@PathVariable String id) {
        return usersService.getUserFrameById(id);
    }
    @PostMapping("/users/forgot-password")
    public Result forgotPassword(@RequestBody Map<String, String> payload) {
        String email = payload.get("email");
        return usersService.forgotPassword(email);
    }

    @PostMapping("/users/reset-password")
    public Result resetPassword(@RequestBody Map<String, String> payload) {
        String token = payload.get("token");
        String newPassword = payload.get("newPassword");
        return usersService.resetPassword(token, newPassword);
    }
}
